package com.ibeeking.found.uaa.cs.config.auth.pwdencoder;

import com.ibeeking.found.uaa.cs.config.advice.CsOAuthException;
import com.ibeeking.nematos.constants.enums.LogClassifyEnum;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.data.StringUtils;
import com.ibeeking.nematos.utils.encryption.EncryptUtils;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.security.KeyPair;

/**
 * @ClassName PasswordEncoder
 * @Description 自定义密码加密校验
 * @Author ibeeking
 * @Date 2020-11-23 11:05
 **/
public class CsPasswordEncoder implements org.springframework.security.crypto.password.PasswordEncoder {

    private KeyPair keyPair;

    public CsPasswordEncoder(KeyPair keyPair) {
        this.keyPair = keyPair;
    }

    @Override
    public String encode(CharSequence rawPassword) {
        return new BCryptPasswordEncoder().encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        } else if (StringUtils.isNotBlank(encodedPassword)) {
            try {
                rawPassword = EncryptUtils.RsaEncrypt.decrypt(rawPassword.toString(), keyPair.getPrivate());
                if (!BCrypt.checkpw(rawPassword.toString(), encodedPassword)) {
                    throw new CsOAuthException("用户名或密码错误");
                }
            } catch (Exception e) {
                LogUtils.warn(LogClassifyEnum.OPERATION_LOG, "全局登录私钥解密失败", e);
                throw new CsOAuthException("用户名或密码错误");
            }
            return new BCryptPasswordEncoder().matches(rawPassword, encodedPassword);
        } else {
            throw new IllegalArgumentException("encodedPassword cannot be null");
        }
    }
}
